
package com.netease.xone.fragment;

import java.io.File;

import net.simonvt.numberpicker.NumberPicker;
import net.simonvt.numberpicker.NumberPicker.OnValueChangeListener;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.meta.User;
import protocol.transactions.TransactionUpload.UploadPrama;
import Utils.XoneUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.netease.image.util.ImageUtil;
import com.netease.log.NTLog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.pkgRelated.XoneConsts.MENU_ID;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityUtil;
import com.netease.xone.app.XoneApp;
import com.netease.xone.dataMgr.CityManager;
import com.netease.xone.image.cropimage.ActivityCropImage;
import com.netease.xone.widget.CustomDialog.OnCustomDlgCancelListener;
import com.netease.xone.widget.LoadingImageView;

public class FragmentEditProfile extends FragmentBase {

    public static final int AVATAR_CROP_LIMIT_SIZE = 256;// 超过大小会报错！

    public static FragmentEditProfile newInstance(User user) {
        FragmentEditProfile f = new FragmentEditProfile();
        Bundle b = new Bundle();
        b.putParcelable(XoneConsts.BUNDLE_KEY.USER_DATA, user);
        f.setArguments(b);
        return f;
    }

    // Views
    private View mAvatarContainer;
    private LoadingImageView mAvatarImage;
    private EditText mNickName;
    private TextView mGender;
    private TextView mBirth;
    private TextView mLocation;
    private EditText mSinature;
    private AlertDialog mSelectPictureDialog;
    private AlertDialog mSelectGenderDialog;
    private AlertDialog mSelectBirthDialog;
    //
    private NumberPicker mProvincePicker;
    private NumberPicker mCityPicker;
    private Dialog mSelectCityDialog;
    // Tid
    private int mUpdateProfileTid;
    private int mUploadTid;
    // Data
    private User mUser;
    private Bitmap mEditAvatarBitmap;
    private CityManager mCityManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mUser = getArguments().getParcelable(XoneConsts.BUNDLE_KEY.USER_DATA);
        XoneService.getInstance().addListener(mCallBack);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_edit_profile, null);
        // find views
        mAvatarContainer = root.findViewById(R.id.profile_avatar_container);
        mAvatarImage = (LoadingImageView)root.findViewById(R.id.profile_avatar);
        mNickName = (EditText)root.findViewById(R.id.profile_nickname);
        mGender = (TextView)root.findViewById(R.id.profile_gender);
        mBirth = (TextView)root.findViewById(R.id.profile_birth);
        mLocation = (TextView)root.findViewById(R.id.profile_location);
        mSinature = (EditText)root.findViewById(R.id.profile_signature);
        // 显示
        mAvatarContainer.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showSelectPicture();
            }
        });
        mAvatarImage.setImageResource(R.drawable.avatar_user_default_110);
        if(!TextUtils.isEmpty(mUser.avatar)){
            mAvatarImage.setLoadingImage(mUser.avatar);
        }
        mGender.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showSelectGender();
            }
        });
        mNickName.setText(mUser.nickname);
        switch (mUser.gender) {
            case 1:
                // 男
                mGender.setText(R.string.male);
                break;
            case 2:
                // 女
                mGender.setText(R.string.female);
                break;
            case 3:
            default:
                // 保密
                mGender.setText(R.string.keep_secrect);
                break;
        }
        if (mUser.birthday != 0) {

        }
        mBirth.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showSelectBirthPicker();
            }
        });

        StringBuilder location = new StringBuilder();
        if (!TextUtils.isEmpty(mUser.province)) {
            location.append(mUser.province).append(" ");
        }
        if (!TextUtils.isEmpty(mUser.city)) {
            location.append(mUser.city);
        }
        mLocation.setText(location.toString());
        mLocation.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                showSelectCity();
            }
        });
        mSinature.setText(mUser.signature);
        return root;
    }

    private void showSelectPicture() {
        if (mSelectPictureDialog == null) {
            mSelectPictureDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.select_picture).setItems(new String[] {
                            getString(R.string.select_from_album), getString(R.string.take_photo)
                    }, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0:
                                    ActivityUtil.selectPictureForResult(FragmentEditProfile.this,
                                            XoneConsts.RESULT_SELECT_PICTURE);
                                    break;
                                case 1:
                                    String path = XoneApp.getAppInstance().getCacheDir().toString()
                                            + File.separator;
                                    if (!new File(path).exists()) {
                                        new File(path).mkdirs();
                                    }
                                    path = path + "avatar_capture_cache.jpg";
                                    ActivityUtil.capturePhotoForResult(FragmentEditProfile.this,
                                            path, XoneConsts.RESULT_CAPTURE_PHOTO);
                                    break;
                            }
                        }
                    }).show();
        } else {
            mSelectPictureDialog.show();
        }
    }

    private void showSelectBirthPicker() {
        if (mSelectBirthDialog == null) {
            final int year = 1980;
            final int month = 0;
            final int day = 1;
            mSelectBirthDialog = new DatePickerDialog(getActivity(), null, year, month, day);
            mSelectBirthDialog.setTitle(R.string.birth);
            mSelectBirthDialog.setCancelable(true);
            mSelectBirthDialog.setButton(Dialog.BUTTON_POSITIVE, getString(R.string.confirm),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            DatePicker dp = ((DatePickerDialog)dialog).getDatePicker();
                            String birth = dp.getYear() + "年" + (dp.getMonth() + 1) + "月"
                                    + dp.getDayOfMonth() + "日";
                            mBirth.setText(birth);
                        }
                    });
            mSelectBirthDialog.setButton(Dialog.BUTTON_NEGATIVE, getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            mSelectBirthDialog.show();
        } else {
            mSelectBirthDialog.show();
        }

    }

    private void showSelectGender() {
        if (mSelectGenderDialog == null) {
            mSelectGenderDialog = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.gender)
                    .setSingleChoiceItems(
                            new String[] {
                                    getString(R.string.keep_secrect), getString(R.string.male),
                                    getString(R.string.female)
                            }, 0, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            mGender.setText(R.string.keep_secrect);
                                            dialog.dismiss();
                                            mUser.gender = 3;
                                            break;
                                        case 1:
                                            mGender.setText(R.string.male);
                                            dialog.dismiss();
                                            mUser.gender = 1;
                                            break;
                                        case 2:
                                            mGender.setText(R.string.female);
                                            dialog.dismiss();
                                            mUser.gender = 2;
                                            break;
                                    }
                                }

                            }).show();
        } else {
            mSelectGenderDialog.show();
        }
    }

    private void showSelectCity() {
        if (mSelectCityDialog == null) {
            mCityManager = new CityManager(getActivity());
            final String[] provinceArray = mCityManager.getProvinces();
            View pickerView = View.inflate(getActivity(), R.layout.view_city_picker, null);
            mProvincePicker = (NumberPicker)pickerView.findViewById(R.id.province_picker);
            mCityPicker = (NumberPicker)pickerView.findViewById(R.id.city_picker);
            mProvincePicker.setMinValue(0);
            mProvincePicker.setMaxValue(provinceArray.length - 1);
            mProvincePicker.setDisplayedValues(provinceArray);
            int provinceIndex = mCityManager.getProvinceIndex(mUser.province);
            if (provinceIndex >= 0) {
                mProvincePicker.setValue(provinceIndex);
            }
            String[] cityArray = mCityManager.getCity(provinceArray[provinceIndex]);
            if (cityArray != null) {
                mCityPicker.setVisibility(View.VISIBLE);
                mCityPicker.setMaxValue(cityArray.length - 1);
                mCityPicker.setMinValue(0);
                mCityPicker.setDisplayedValues(cityArray);
                int cityIndex = mCityManager.getCityIndex(mUser.province, mUser.city);
                if (cityIndex >= 0)
                    mCityPicker.setValue(cityIndex);
            } else {
                mCityPicker.setMaxValue(0);
                mCityPicker.setMinValue(0);
                mCityPicker.setVisibility(View.INVISIBLE);
            }
            mProvincePicker.setOnValueChangedListener(new OnValueChangeListener() {

                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    final String[] cityArray = mCityManager.getCity(provinceArray[picker.getValue()]);
                    try {
                        if (cityArray != null) {
                            mCityPicker.setVisibility(View.VISIBLE);
                            mCityPicker.setDisplayedValues(null);
                            mCityPicker.setMaxValue(cityArray.length - 1);
                            mCityPicker.setMinValue(0);
                            mCityPicker.setDisplayedValues(cityArray);
                        } else {
                            mCityPicker.setVisibility(View.INVISIBLE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();// 快速滑动Picker时有时会异常，这里保护一下
                    }
                }
            });
            mSelectCityDialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.city)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mUser.province = mCityManager.getProvinceString(mProvincePicker
                                    .getValue());
                            mUser.city = mCityManager.getCityString(mProvincePicker.getValue(),
                                    mCityPicker.getValue());
                            StringBuilder location = new StringBuilder();
                            if (!TextUtils.isEmpty(mUser.province)) {
                                location.append(mUser.province).append(" ");
                            }
                            if (!TextUtils.isEmpty(mUser.city)) {
                                location.append(mUser.city);
                            }
                            mLocation.setText(location.toString());
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mSelectCityDialog.dismiss();
                        }
                    }).setView(pickerView).show();
        } else {
            mSelectCityDialog.show();
        }
    }

    private boolean beforeEdit() {
        // check nickname
        String nickName = mNickName.getText().toString();
        if (XoneUtil.isNicknameContainsSpecialChar(nickName)) {
            Toast.makeText(getActivity(), R.string.error_nickname_illegal_character,
                    Toast.LENGTH_SHORT).show();
            return false;
        }
        if (XoneUtil.getNicknameLen(nickName) < 4 || XoneUtil.getNicknameLen(nickName) > 16) {
            Toast.makeText(getActivity(), R.string.error_nickname_number, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        String signature = mSinature.getText().toString();
        if (XoneUtil.getNicknameLen(signature) > 140) {
            Toast.makeText(getActivity(), R.string.error_signature_number, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }
        mUser.nickname = nickName;
        mUser.signature = mSinature.getText().toString();
        return true;
    }

    private void doEditProfile() {
        if (!beforeEdit())
            return;

        // 开始发送
        showCustomDialog(getActivity(), "正在保存", mOnCustomDlgCancelListener);
        if (mEditAvatarBitmap != null) {
            // 头像有修改，上传头像
            // TODO 获取临时缓存目录
            String path = XoneApp.getAppInstance().getCacheDir().toString() + File.separator;
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            path = path + "temp_crop_avatar.jpg";
            if (ImageUtil.saveBitMaptoFile(mEditAvatarBitmap, path)) {
                // 压缩图片成功，准备上传
                UploadPrama para = new UploadPrama();
                para.type = UploadPrama.TYPE_IMAGE;
                para.path = path;
                mUploadTid = XoneService.getInstance().doUpload(para);
            } else {
                // 一般不会到这里
                Toast.makeText(getActivity(), "存储头像失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 头像无修改，直接更新
            mUpdateProfileTid = XoneService.getInstance().doUpdateUser(mUser);
        }
    }

    private OnCustomDlgCancelListener mOnCustomDlgCancelListener = new OnCustomDlgCancelListener() {

        @Override
        public void onCancel() {
            XoneService.getInstance().cancelTransaction(mUpdateProfileTid);
        }
    };

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onUpload(int transactionId, Object obj) {
            NTLog.d("EditProfile", "avatar upload success:" + obj);
            if (transactionId == mUploadTid) {
                NTLog.d("EditProfile", "avatar upload success:" + obj);
                String url = obj.toString();
                mUser.avatar = url;
                mEditAvatarBitmap = null;
                mUpdateProfileTid = XoneService.getInstance().doUpdateUser(mUser);
            }
        };

        @Override
        public void onUploadError(int transactionId, int errCode, String err) {
            // TODO 头像上传失败
            NTLog.d("EditProfile", "avatar upload fail:" + err);
        };

        @Override
        public void onUpdateUser(int transactionId) {
            if (transactionId == mUpdateProfileTid) {
                closeCustomDialog();
                Toast.makeText(getActivity(), R.string.success_edit_profile, Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        };

        @Override
        public void onUpdateUserError(int transactionId, int errCode, String err) {
            if (transactionId == mUpdateProfileTid) {
                closeCustomDialog();
                Toast.makeText(getActivity(), err, Toast.LENGTH_SHORT).show();
            }
        };
    };

    @Override
    public void onDestroy() {
        XoneService.getInstance().removeListener(mCallBack);
        super.onDestroy();
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case XoneConsts.RESULT_SELECT_PICTURE: {
                    Uri uri = data.getData();
                    // 屏幕宽度的bitmap
                    Bitmap scaleBitmap = ImageUtil.getBitmapFromUriLimitSize(getActivity(), uri,
                            AVATAR_CROP_LIMIT_SIZE);
                    ActivityCropImage.actionGetCropImage(this, XoneConsts.RESULT_IMAGE_CORP,
                            scaleBitmap, true);
                    break;
                }
                case XoneConsts.RESULT_CAPTURE_PHOTO: {
                    Uri uri = data.getData();
                    // 屏幕宽度的bitmap
                    Bitmap scaleBitmap = ImageUtil.getBitmapFromUriLimitSize(getActivity(), uri,
                            AVATAR_CROP_LIMIT_SIZE);
                    ActivityCropImage.actionGetCropImage(this, XoneConsts.RESULT_IMAGE_CORP,
                            scaleBitmap, true);
                    break;
                }
                case XoneConsts.RESULT_IMAGE_CORP:
                    Bitmap bitmap = data.getExtras().getParcelable(ActivityCropImage.EXTRA_DATA);
                    mAvatarImage.setImageBitmap(bitmap);
                    mEditAvatarBitmap = bitmap;
                    break;
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.add(0, MENU_ID.menu_edit_profile_confirm, 0, "")
                .setIcon(R.drawable.icon_action_done_selector)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_ID.menu_edit_profile_confirm:
                doEditProfile();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
